package models

import (
	"fmt"
	"log"

	"github.com/beego/beego/v2/core/config"
	"github.com/go-xorm/xorm"
	"xorm.io/core"

	_ "github.com/go-sql-driver/mysql"
)

var engine *xorm.Engine
var Engine *xorm.Engine

func init() {
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Fatal("配置文件载入错误")
	}

	dbSection, err := conf.GetSection("db")
	if err != nil {
		log.Fatal("配置文件载入错误-数据库-section载入失败")
	}

	dbHost := dbSection["db_host"]
	dbPort := dbSection["db_port"]
	dbUser := dbSection["db_user"]
	dbPass := dbSection["db_pass"]
	dbName := dbSection["db_name"]

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", dbUser, dbPass, dbHost, dbPort, dbName)

	log.Println("数据库DSN: " + dsn)

	engine, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		log.Fatal("数据库链接失败")
	}

	engine.SetTableMapper(core.NewPrefixMapper(core.SnakeMapper{}, ""))

	engine.ShowSQL(true)
	engine.ShowExecTime(true)
	if err := engine.Ping(); err != nil {
		fmt.Println(err.Error())
	}
	Engine = engine
}
